﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/24 9:35:26
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using CommonLibrary;
using CommonLibrary.Forms;


namespace SCADA.BLL
{
    /// <summary>
    /// 记录查询界面
    /// </summary>
    public partial class FormRecordQuery : HWFrmWithTitle
    {
        /// <summary>
        /// 每页数量
        /// </summary>
        private int mNumOfSinglePage = 1000;
        /// <summary>
        /// 当前页
        /// </summary>
        private int mCurrentPage = 1;
        /// <summary>
        /// 最小页码
        /// </summary>
        private int mMinPage = 1;
        /// <summary>
        /// 最大页码
        /// </summary>
        private int mMaxPage = 1;
        /// <summary>
        /// 已查询到的记录
        /// </summary>
        private List<ProductInfo> mList = new List<ProductInfo>();
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormRecordQuery()
        {
            InitializeComponent();
            this.Icon = Program.ICON;
        }
        /// <summary>
        /// 初始化数据显示控件
        /// </summary>
        public void OutboundListViewInit()
        {
            CommonHelper.InitDataGridViewColumns<ProductInfo>(this.dataGridViewProduct);
        }
        private void ShowMessage(string message)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    ShowMessage(message);
                }));
            }
            else
            {
                HWMessageBox.Show(this, message);
            }
        }
        private bool IsValidDateRange()
        {
            bool isValid = false;
            int maxDays = BusinessConfig.Instance().MaxDaysInQueryData;
            try
            {
                double days = this.dateTimePickerEndTime.Value.Subtract(this.dateTimePickerStartTime.Value).TotalDays;
                isValid = days >= 0 && days <= maxDays;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            if (!isValid)
            {
                ShowMessage($"时间范围有误，请别超过 {maxDays} 天");
            }
            return isValid;
        }
        private void ExecQueryData()
        {
            if (this.dataGridViewProduct.InvokeRequired)
            {
                this.dataGridViewProduct.Invoke(new Action(() => { ExecQueryData(); }));
            }
            else
            {
                CommonHelper.ShowWaiting(this, "查询中，请稍候......");
                InitPage(false, 1, 1, 1);


                this.mList = new List<ProductInfo>();
                this.dataGridViewProduct.Rows.Clear();
                string startTime = dateTimePickerStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                string endTime = dateTimePickerEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                string barcode = textBoxBarcode.Text.Trim();
                try
                {
                    this.mList = ProductSQLiteDb.GetProductInfoAllList(barcode, startTime, endTime);
                    int recordCount = this.mList != null && this.mList.Count > 0 ? this.mList.Count : 0;
                    groupBoxRecord.Text = $"查询到 {recordCount} 条记录";
                    this.mMaxPage = (int)Math.Ceiling(recordCount * 1.0 / this.mNumOfSinglePage);
                    AddDataToGrid(0, this.mNumOfSinglePage - 1);
                }
                catch (Exception ex)
                {
                    ShowMessage(ex.Message);
                    LogHelper.Error(ex);
                }
                InitPage(true, 1, 1, this.mMaxPage);
                CommonHelper.CloseWaiting();
                Application.DoEvents();
            }
        }
        private void QueryData()
        {
            new Thread(() =>
            {
                ExecQueryData();
            })
            { IsBackground = true }.Start();
            Application.DoEvents();
        }
        /// <summary>
        /// 数据查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonQuery_Click(object sender, EventArgs e)
        {
            if (IsValidDateRange())
            {
                QueryData();
                Application.DoEvents();
            }
        }
        /// <summary>
        /// 页码初始化
        /// </summary>
        /// <param name="enabled"></param>
        /// <param name="currentPage"></param>
        /// <param name="minPage"></param>
        /// <param name="maxPage"></param>
        private void InitPage(bool enabled, int currentPage, int minPage, int maxPage)
        {
            this.panelPage.Enabled = enabled;
            this.mCurrentPage = currentPage;
            this.mMinPage = minPage;
            this.mMaxPage = maxPage;
            this.labelCurrent.Text = $"当前页码：{this.mCurrentPage}";
            this.labelTotal.Text = $"总页码：{this.mMaxPage}";
        }
        /// <summary>
        /// 数据显示到控件代理
        /// </summary>
        /// <param name="productInfos"></param>
        public delegate void AddDataToGridDelegate(List<ProductInfo> productInfos);
        /// <summary>
        /// 数据显示到控件中
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        public void AddDataToGrid(int startIndex, int endIndex)
        {
            CommonHelper.ShowWaiting(this, "数据展示中，请稍候......");
            this.dataGridViewProduct.Rows.Clear();
            new Thread(() =>
            {
                ExecAddDataToGrid(startIndex, endIndex);
            })
            { IsBackground = true }.Start();
            Application.DoEvents();
        }
        private void ExecAddDataToGrid(int startIndex, int endIndex)
        {
            if (this.dataGridViewProduct.InvokeRequired)
            {
                this.dataGridViewProduct.Invoke(new Action(() =>
                {
                    ExecAddDataToGrid(startIndex, endIndex);
                }));
            }
            else
            {
                try
                {
                    ProductInfo productInfo = new ProductInfo();
                    System.Reflection.PropertyInfo[] properties = productInfo.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    if (this.mList != null && this.mList.Count > 0)
                    {
                        endIndex = endIndex > this.mList.Count ? this.mList.Count - 1 : endIndex;
                        for (var j = startIndex; j <= endIndex; j++)
                        {
                            var p = this.mList[j];
                            var row = this.dataGridViewProduct.Rows[this.dataGridViewProduct.Rows.Add(1)];
                            row.Cells[0].Value = (j + 1);
                            row.Cells[0].Style.ForeColor = p.GetForeColor("Id");
                            row.Cells[0].Style.SelectionForeColor = row.Cells[0].Style.ForeColor;
                            for (var i = 1; i < this.dataGridViewProduct.Columns.Count; i++)
                            {
                                var column = this.dataGridViewProduct.Columns[i];
                                var pInfo = properties.Where(v => v.Name == column.Name).FirstOrDefault();
                                if (pInfo != null)
                                {
                                    object objValue = pInfo.GetValue(p);
                                    string strValue = objValue == null || string.IsNullOrWhiteSpace(objValue.ToString()) ? "-" : objValue.ToString();
                                    row.Cells[i].Value = strValue;
                                    row.Cells[i].Style.ForeColor = p.GetForeColor(pInfo.Name);
                                    row.Cells[i].Style.SelectionForeColor = row.Cells[i].Style.ForeColor;
                                }
                                else
                                {
                                    row.Cells[i].Value = "-";
                                }
                            }
                            row.Tag = p;
                        }
                    }
                    Application.DoEvents();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
                CommonHelper.CloseWaiting();
            }
        }
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormRecordQuery_Load(object sender, EventArgs e)
        {
            OutboundListViewInit();
            DateTime now = DateTime.Now;
            this.dateTimePickerEndTime.Value = DateTime.Parse(now.ToString("yyyy-MM-dd HH:mm:59"));
            this.dateTimePickerStartTime.Value = DateTime.Parse(now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:00"));
            this.labelStart.Select();
        }
        /// <summary>
        /// 导出按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOutput_Click(object sender, EventArgs e)
        {
            if (IsValidDateRange())
            {
                DirectlyOutputToExcel();
                Application.DoEvents();
            }
        }
        /// <summary>
        /// 通过条件查询数据并导出到Excel文档中
        /// </summary>
        private void DirectlyOutputToExcel()
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "*.xlsx|*.xlsx";
            DialogResult result = dialog.ShowDialog();
            string startTime = dateTimePickerStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
            string endTime = dateTimePickerEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
            string barcode = textBoxBarcode.Text.Trim();
            new Thread(() =>
            {
                if (result == DialogResult.OK)
                {
                    CommonHelper.ShowWaiting(this, "正在导出数据，请稍候......");
                    try
                    {
                        List<ProductInfo> list = ProductSQLiteDb.GetProductInfoAllList(barcode, startTime, endTime);
                        bool outputResult = CommonHelper.WriteExcel(dialog.FileName, list, true, "数据", (message) => { CommonHelper.ShowWaiting(this, message); }, true);
                        if (outputResult)
                        {
                            ShowMessage("导出成功");
                            CommonHelper.OpenExcelFile(dialog.FileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                        LogHelper.Error(ex);
                    }
                }
                CommonHelper.CloseWaiting();
            })
            { IsBackground = true }.Start();
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonPrev_Click(object sender, EventArgs e)
        {
            if (this.mCurrentPage > this.mMinPage)
            {
                this.mCurrentPage--;
                this.labelCurrent.Text = $"当前页码：{this.mCurrentPage}";
                int startIndex = (this.mCurrentPage - 1) * this.mNumOfSinglePage;
                int endIndex = this.mCurrentPage * this.mNumOfSinglePage - 1;
                AddDataToGrid(startIndex, endIndex);
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonNext_Click(object sender, EventArgs e)
        {
            if (this.mCurrentPage < this.mMaxPage)
            {
                this.mCurrentPage++;
                this.labelCurrent.Text = $"当前页码：{this.mCurrentPage}";
                int startIndex = (this.mCurrentPage - 1) * this.mNumOfSinglePage;
                int endIndex = this.mCurrentPage * this.mNumOfSinglePage - 1;
                AddDataToGrid(startIndex, endIndex);
            }
        }
        private void FormRecordQuery_Shown(object sender, EventArgs e)
        {
        }
        private void FormRecordQuery_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
    }

}
